'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class UserController extends Controller {
    async login() {
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(/^\w{5}$/.test(username) && password){
            let list = await service.user.login(username,password);
            if(list.length){
                let token = jwt.sign({username,password},'zk3',{expiresIn:60*60*4});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    async registry() {
        let {ctx,service} = this;

        let {num,username,email,password} = ctx.request.body;
        //1.参数的校验
        if(/^\w{5}$/.test(username) && password && /^\w{5}$/.test(num) && email){
            //2.排重
            let target = await service.user.selectUser(num);
            if(target.length){
                //此账号已被使用
                ctx.body = {
                    code:3,
                    msg:'此账号已存在'
                }
            }else{
                //3.注册
                try{
                    await service.user.registry(num,username,email,password);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
